package com.chhuang.ewcrm.ctrl;

import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.application.LoginApp;
import com.chhuang.ewcrm.application.RootApp;
import com.chhuang.ewcrm.bean.FXMLBean;
import com.chhuang.ewcrm.bean.MainMenuBean;
import com.chhuang.ewcrm.config.PropertiesUtil;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WMenuDao;
import com.chhuang.ewcrm.dao.WUserMenuDao;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.entity.WMenu;
import com.chhuang.ewcrm.entity.WUserMenu;
import com.chhuang.ewcrm.utils.MyPath;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialog;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

/**
 * 主界面
 * @author chhuang
 * @create 2020-09-11-9:14
 */
public class RootController implements Initializable {
    private final Logger logger = LoggerFactory.getLogger(RootController.class);

    @FXML
    private TabPane centerTabPane;//中间工作区

    @FXML
    private MenuBar wMenuBar;

    @FXML
    private ImageView userIconImageView;//用户头像

    @FXML
    private StackPane rootStackPane;

    @FXML
    private JFXDialog dialog;
    @FXML
    private JFXButton dialogAcceptButton;

    private final WMenuDao wMenuDao = App.getSession().getMapper(WMenuDao.class);
    private final WUserMenuDao wUserMenuDao = App.getSession().getMapper(WUserMenuDao.class);

    private static String BASE_URL = PropertiesUtil.getValue(MyPath.getConfigPath()+Constants.PROPERTIES_FILE_NAME, Constants.PS_BASE_URL_STR);

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        dialog.setTransitionType(JFXDialog.DialogTransition.RIGHT);
        dialog.setDialogContainer(rootStackPane);

        if(Constants.loginUser!=null && StringUtils.isNotEmpty(Constants.loginUser.getUserphoto())){
            Image userPhoto = new Image(BASE_URL+Constants.loginUser.getUserphoto());
            userIconImageView.setImage(userPhoto);
        }

        changeCenter(new FXMLBean("计量称重", "/fxml/weigh.fxml"));

        ObservableList<Menu> menus =wMenuBar.getMenus();
        for(MainMenuBean mainMenu : Constants.MAIN_MENUS){
            Menu menu = new Menu();
            menu.setMnemonicParsing(false);
            menu.setText(mainMenu.getMenuName());
            menu.setId(String.valueOf(mainMenu.getMenuId()));
            ObservableList<MenuItem> menuItems = menu.getItems();

            SysUser loginUser = Constants.loginUser;

            if("005".equals(loginUser.getRoleId())){ //过磅员
                WUserMenu wUserMenu = new WUserMenu();
                wUserMenu.setParentMenuId(mainMenu.getMenuId());
                wUserMenu.setUserId(Constants.loginUser.getUserId());
                List<WUserMenu> wUserMenus = wUserMenuDao.query(wUserMenu);
                if(wUserMenus!=null && !wUserMenus.isEmpty()){
                    for(WUserMenu item : wUserMenus){
                        MenuItem menuItem = new MenuItem();
                        menuItem.setMnemonicParsing(false);
                        menuItem.setText(item.getMenuName());
                        menuItem.setId(item.getFxmlUrl());
                        menuItem.setOnAction(this::openTab);
                        menuItems.add(menuItem);
                    }
                }
            }else if("001".equals(loginUser.getRoleId())){//管理员
                WMenu wMenu = new WMenu();
                wMenu.setParentMenuId(mainMenu.getMenuId());
                List<WMenu> wMenus = wMenuDao.query(wMenu);
                if(wMenus!=null && !wMenus.isEmpty()){
                    for (WMenu mtemp : wMenus){
                        MenuItem menuItem = new MenuItem();
                        menuItem.setMnemonicParsing(false);
                        menuItem.setText(mtemp.getMenuName());
                        menuItem.setId(mtemp.getFxmlUrl());
                        menuItem.setOnAction(this::openTab);
                        menuItems.add(menuItem);
                    }
                }
            }

            if(menuItems!=null && !menuItems.isEmpty())
                menus.add(menu);
        }

        //
        dialogAcceptButton.setOnAction(event -> {
            dialog.close();
        });
    }

    /**
     * 菜单栏显示指定的页签
     * @param event
     */
    @FXML
    public void openTab(ActionEvent event){
        MenuItem menuItem = (MenuItem) event.getSource();
        String id = menuItem.getId();
        if(StringUtils.isNotEmpty(id))
            changeCenter(new FXMLBean(menuItem.getText(), id));
    }

    /**
     * 工具栏显示指定的页签
     * @param event
     */
    @FXML
    public void showTab(ActionEvent event){
        JFXButton button = (JFXButton) event.getSource();
        changeCenter(new FXMLBean(button.getText(), button.getId()));
    }

    /**
     * 重新登录
     */
    @FXML
    public void changeUser(ActionEvent event){
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认退出");
        alert.setHeaderText("您确定要退出登录吗？");
        Optional<ButtonType> result = alert.showAndWait();
        if(result.get() == ButtonType.OK){
            ObservableList<Tab> tabs = centerTabPane.getTabs();
            if(tabs!=null && !tabs.isEmpty()){
                for(Tab tab : tabs){
                    EventHandler<Event> handler = tab.getOnCloseRequest();
                    if(handler!=null){
                        handler.handle(null);
                    }
                }
            }
            centerTabPane.getTabs().clear();
            new LoginApp().start(new Stage());
            ((Stage) ((Node) event.getSource()).getScene().getWindow()).close();
        }else {
            event.consume();
        }
    }

    /**
     * 退出系统
     * @param event
     */
    @FXML
    public void exit(ActionEvent event){
        RootApp.close(event);
    }

    /**
     * 跳转控制台页面
     * @param fxmlBean
     */
    public void changeCenter(FXMLBean fxmlBean){
        try {
            Tab selectTab = null;
            ObservableList<Tab> tabs = centerTabPane.getTabs();
            if(tabs!=null && !tabs.isEmpty()){
                for(Tab tab : tabs){
                    if(fxmlBean.getUrl().equals(tab.getId())) {
                        selectTab = tab;
                        break;
                    }
                }
            }
            if(selectTab==null){
                URL url = this.getClass().getResource(fxmlBean.getUrl());
                FXMLLoader fxmlLoader = new FXMLLoader();
                fxmlLoader.setLocation(url);
                fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
                Node node = fxmlLoader.load(url.openStream());
//                Node node = FXMLLoader.load(getClass().getResource(fxmlBean.getUrl()));
                final InitController controller = fxmlLoader.getController();
                selectTab = new Tab(fxmlBean.getName());
                selectTab.setId(fxmlBean.getUrl());
                selectTab.setContent(node);
                selectTab.setOnCloseRequest(event -> controller.close());
                centerTabPane.getTabs().add(selectTab);
            }
            centerTabPane.getSelectionModel().select(selectTab);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
